package com.sk.sourcecircle.activity.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.google.zxing.WriterException;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.home.fragment.GroupCircleFragment;
import com.sk.sourcecircle.activity.home.fragment.GroupConsultFragment;
import com.sk.sourcecircle.activity.home.fragment.GroupReleaseFragment;
import com.sk.sourcecircle.activity.home.fragment.GroupShareFragment;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.activity.mine.act.PersonlCodeActivity;
import com.sk.sourcecircle.adapter.MyPagerAdapter;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.GroupDetailsBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.NoticeView;
import com.sk.sourcecircle.view.StarBar;
import com.sk.sourcecircle.zxing.encoding.EncodingHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2017/12/13.
 */

public class GroupDetailsActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.group_bg)
    ImageView groupBg;
    @BindView(R.id.group_head)
    ImageView groupHead;
    @BindView(R.id.group_name)
    TextView groupName;
    @BindView(R.id.add_care)
    TextView addCare;
    @BindView(R.id.cancel_care)
    TextView cancelCare;
    @BindView(R.id.des_star)
    StarBar desStar;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_prove)
    TextView tvProve;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.my_table)
    TabLayout myTable;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.my_pager)
    ViewPager myPager;

    GroupReleaseFragment groupReleaseFragment;
    GroupConsultFragment groupConsultFragment;
    GroupCircleFragment groupCircleFragment;
    GroupShareFragment groupShareFragment;
    @BindView(R.id.care_ll)
    FrameLayout careLl;
    @BindView(R.id.group_code)
    ImageView groupCode;
    @BindView(R.id.notice_view)
    NoticeView noticeView;
    @BindView(R.id.vip)
    ImageView vip;
    private int groupId;
    private String url = "";
    private boolean isCare = false;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isCare() {
        return isCare;
    }

    public void setCare(boolean care) {
        isCare = care;
    }

    public int getGroupId() {
        return groupId;
    }

    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }

    private List<Fragment> fragmentList = new ArrayList<>();

    private LoadingDialog loadingDialog;

    private String name = "";

    public static final int Group = 10;


    @Override
    protected int getContentView() {
        return R.layout.activity_group_details;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        loadingDialog.show();
        groupId = getIntent().getIntExtra("id", 0);
        noticeView.getNotice(String.valueOf(groupId));
        AppApi.getGroupDetails(groupId, this, 0, this);
        initFragments();

        Bitmap mBitmap = null;
        try {
            mBitmap = EncodingHandler.createQRCode("type=0&id=" + String.valueOf(MyUtils.getCode(mContext)), 300);
            groupCode.setImageBitmap(mBitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerEvent(String s) {
        if (s.equals("msg")) {
            groupCircleFragment.doRefresh();
        }
    }

    private void initFragments() {

        groupReleaseFragment = new GroupReleaseFragment();
        groupConsultFragment = new GroupConsultFragment();
        groupCircleFragment = new GroupCircleFragment();
        groupShareFragment = new GroupShareFragment();

        fragmentList.add(groupReleaseFragment);
        fragmentList.add(groupConsultFragment);
        fragmentList.add(groupCircleFragment);
        fragmentList.add(groupShareFragment);

        myPager.setOffscreenPageLimit(4);
        MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager(), getResources().getStringArray(R.array.group_array), fragmentList);
        myPager.setAdapter(adapter);
        myTable.setupWithViewPager(myPager);

    }

    @OnClick({R.id.back, R.id.add_care, R.id.cancel_care, R.id.group_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.add_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, Group);
                    return;
                }
                loadingDialog.show();
                AppApi.addCareGroup(groupId, GroupDetailsActivity.this, 1, GroupDetailsActivity.this);
                break;
            case R.id.cancel_care:
                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(intent, Group);
                    return;
                }
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setContent("确认取消关注此社群？");
                tipDialogFragment.setMyCallBack(GroupDetailsActivity.this);
                tipDialogFragment.show(getSupportFragmentManager(), "tip");
                break;
            case R.id.group_code:
                Intent intent = new Intent(mContext, PersonlCodeActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("string", "type=0&id=" + groupId);
                intent.putExtra("name", name);
                intent.putExtra("url", url);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                GroupDetailsBean groupDetailsBean = JSON.parseObject(result, GroupDetailsBean.class);
                Glide.with(mContext).load(groupDetailsBean.getData().getCommunity_image()).into(groupHead);
                url = groupDetailsBean.getData().getCommunity_image();
                tvDescribe.setText(groupDetailsBean.getData().getIntroduce());
                tvLocation.setText("所在地：" + groupDetailsBean.getData().getCity() + " " + groupDetailsBean.getData().getSincerity());
                groupName.setText(groupDetailsBean.getData().getCommunity_name());
                name = groupDetailsBean.getData().getCommunity_name();
                desStar.setStarMark(groupDetailsBean.getData().getSincerity() / 5f);
                switch (groupDetailsBean.getData().getType()) {
                    case 1:
                        vip.setVisibility(View.VISIBLE);
                        vip.setImageResource(R.mipmap.group_vip);
                        tvProve.setText("源圈认证：官方账号");
                        break;
                    case 2:
                        vip.setVisibility(View.VISIBLE);
                        vip.setImageResource(R.mipmap.vip_icon);
                        tvProve.setText("源圈认证：公司账号");
                        break;
                    case 3:
                        vip.setVisibility(View.VISIBLE);
                        vip.setImageResource(R.mipmap.person_vip);
                        tvProve.setText("源圈认证：个人账号");
                        break;
                }
                if (groupDetailsBean.getData().getFollow() == 1) {
                    cancelCare.setVisibility(View.VISIBLE);
                    addCare.setVisibility(View.GONE);
                    isCare = true;
                } else {
                    cancelCare.setVisibility(View.GONE);
                    addCare.setVisibility(View.VISIBLE);
                    isCare = false;
                }
                break;
            case 1:
                cancelCare.setVisibility(View.VISIBLE);
                addCare.setVisibility(View.GONE);
                isCare = true;
                SnackUtils.show(mRootView, "关注成功！");
                groupCircleFragment.doRefersh();
                break;
            case 2:
                cancelCare.setVisibility(View.GONE);
                addCare.setVisibility(View.VISIBLE);
                isCare = false;
                SnackUtils.show(mRootView, "取关成功！");
                groupCircleFragment.doRefersh();
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void sure() {
        super.sure();
        loadingDialog.show();
        AppApi.cancelCareGroup(groupId, GroupDetailsActivity.this, 2, GroupDetailsActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == Group) {
                loadingDialog.show();
                AppApi.getGroupDetails(groupId, this, 0, this);
                groupCircleFragment.doRefersh();
                groupShareFragment.doRefresh();
            }
        }
    }
}
